<template>
  <div class="login">
    <van-form validate-first @failed="onFailed" @submit="handleSubmit">
      <!-- 通过 pattern 进行用户名正则校验 -->
      <van-field
        v-model.trim="username"
        autocomplete
        label="用户名"
        name="用户名"
        placeholder="请输入用户名"
        :rules="[{ pattern: patternUsername, message: '用户名由6-16位数字、字母、下划线组成' }]"
      />
      <!-- 通过 pattern 进行密码正则校验 -->
      <van-field
        v-model.trim="password"
        autocomplete
        label="密码"
        name="密码"
        type=password
        placeholder="请输入密码"
        :rules="[{ pattern: patternPassword, message: '密码由8-16位数字、字母、下划线组成' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
    <div style="margin: 16px;">
      <van-button round block plain type="info" to="/register" replace>切换到注册</van-button>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { Toast } from 'vant'
Vue.use(Toast)
export default {
  name: 'login',
  data () {
    return {
      username: '',
      password: '',
      patternUsername: /^[0-9a-zA-Z_]{6,16}$/,
      patternPassword: /^[0-9a-zA-Z_]{8,16}$/,
      timeout: '',
    }
  },
  methods: {
    onFailed (errorInfo) {
      Toast.fail(errorInfo.errors[0].name + '格式\n不正确')
    },
    handleSubmit () {
      if (!this.$store.state.userInfo.filter(user => user.username === this.username).length) {
        Toast.fail('该账号未注册')
        return
      }
      if (!this.$store.state.userInfo.filter(user => user.username === this.username && user.password === this.password).length) {
        Toast.fail('密码错误')
        return
      }
      // 提示登录成功
      Toast.success({
        message: '登录成功',
        forbidClick: true,
      })
      // 将账号信息添加到 vuex
      this.$store.commit('handleuseInfo', {
        username: this.username,
      })
      // 1 秒之后跳转到 collect 页面，提升用户体验
      this.timeout = setTimeout(() => {
        this.$router.push({
          name: 'mine',
        })
      }, 1000)
    },
  },
  beforeDestroy () {
    clearTimeout(this.timeout)
  },
}
</script>

<style lang="less" scoped>

</style>
